package product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feign.coupon.CouponFeignService;
import com.feign.to.SkuReductionTo;
import com.feign.to.SpuBoundTo;
import com.feign.utils.R;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import product.domain.*;
import product.domain.Attr;
import product.mapper.SkuInfoMapper;
import product.service.*;
import product.mapper.SpuInfoMapper;
import org.springframework.stereotype.Service;
import product.vo.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author panghu
 * @description 针对表【pms_spu_info(spu信息)】的数据库操作Service实现
 * @createDate 2023-03-04 21:03:08
 */
@Service
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo>
        implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuInfoMapper skuInfoMapper;


    @Override
    public Page<SpuInfo> querPage(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfo> queryWrapper = getQueryWrapper(params);
        Page<SpuInfo> spuInfoPage = new Page<>(Integer.parseInt((String) params.get("page")), Integer.parseInt((String) params.get("limit")));
        return this.baseMapper.selectPage(spuInfoPage, queryWrapper);
    }

    @Override
    public void spuUP(Long id) {
        SpuInfo spuInfo = new SpuInfo();
        spuInfo.setId(id);
        spuInfo.setPublishStatus(1);
        this.updateById(spuInfo);
    }

    @Override
    public SpuInfo findSpuInfoBySkuId(Long skuId) {
        SkuInfo skuInfo = skuInfoMapper.selectOne(new LambdaQueryWrapper<SkuInfo>().eq(SkuInfo::getSkuId, skuId));
        return this.baseMapper.selectOne(new LambdaQueryWrapper<SpuInfo>().eq(SpuInfo::getId, skuInfo.getSpuId()));
    }

    private LambdaQueryWrapper<SpuInfo> getQueryWrapper(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(params.containsKey("key"), SpuInfo::getSpuName, params.get("key")).or().like(params.containsKey("key"), SpuInfo::getSpuDescription, params.get("key"));
        wrapper.eq(params.containsKey("catelogId"), SpuInfo::getCatalogId, params.get("catelogId"));
        wrapper.eq(params.containsKey("brandId"), SpuInfo::getBrandId, params.get("brandId"));
        wrapper.eq(params.containsKey("status"), SpuInfo::getPublishStatus, params.get("status"));
        return wrapper;
    }

    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo spuSaveVo) {
        // 1、保存spu基本信息：pms_spu_info
        SpuInfo spuInfo = new SpuInfo();
        BeanUtils.copyProperties(spuSaveVo, spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfo);
        // 2、保存spu的描述图片:pms_spu_info_desc
        List<String> descript = spuSaveVo.getDecript();
        SpuInfoDesc spuInfoDesc = new SpuInfoDesc();
        spuInfoDesc.setSpuId(spuInfo.getId());
        spuInfoDesc.setDecript(String.join(",", descript));
        spuInfoDescService.save(spuInfoDesc);
        // 3、保存spu的图片集:pms_spu_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfo.getId(), images);
        // 4、保存spu的规格参数:pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValue> productAttrValues = baseAttrs.stream().map(attr -> {
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setAttrId(attr.getAttrId());
            Attr id = attrService.getById(attr.getAttrId());
            productAttrValue.setAttrName(id.getAttrName());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setSpuId(spuInfo.getId());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValues);
        // 5、保存spu的积分信息:gulimall_sms->sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfo.getId());
        R r1 = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r1.getCode() != 200) {
            log.error("远程保存spu积分信息失败");
        }
        List<Skus> skus = spuSaveVo.getSkus();
        // 6、保存当前spu对应的所有sku信息；
        if (!ObjectUtils.isEmpty(skus)) {
            skus.forEach(sku -> {
                String defaultImg = "";
                List<Images> imagesList = sku.getImages();
                for (Images img : imagesList) {
                    if (img.getDefaultImg() == 1) {
                        defaultImg = img.getImgUtl();
                    }
                }
                SkuInfo skuInfo = new SkuInfo();
                BeanUtils.copyProperties(sku, skuInfo);
                skuInfo.setBrandId(spuInfo.getBrandId());
                skuInfo.setCatalogId(spuInfo.getCatalogId());
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(spuInfo.getId());
                skuInfo.setSkuDefaultImg(defaultImg);
                // 6.1)sku的基本信息。pms_sku_info
                skuInfoService.save(skuInfo);
                Long skuId = skuInfo.getSkuId();
                List<SkuImages> skuImagesList = sku.getImages().stream().map(img -> {
                    SkuImages skuImages = new SkuImages();
                    skuImages.setSkuId(skuId);
                    skuImages.setImgUrl(img.getImgUtl());
                    skuImages.setDefaultImg(img.getDefaultImg());
                    return skuImages;
                }).filter(entity -> !ObjectUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                // 6.2)sku的图片信息。pms_sku_images
                skuImagesService.saveBatch(skuImagesList);
                // 6.3)sku的销售属性信息。pms_sku_sale_attr_value
                List<SkuSaleAttrValue> skuSaleAttrValueList = sku.getAttr().stream().map(attr -> {
                    SkuSaleAttrValue skuSaleAttrValue = new SkuSaleAttrValue();
                    BeanUtils.copyProperties(attr, skuSaleAttrValue);
                    skuSaleAttrValue.setSkuId(skuId);
                    return skuSaleAttrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueList);
                // 6.4)sku的优惠券、满贱等信息：mall_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price\sms_spu_bounds
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) > 0) {
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 200) {
                        log.error("远程保存sku优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfo spuInfo) {
        this.baseMapper.insert(spuInfo);
    }


}




